package jou.cs.service.impl;

import jou.cs.configurator.CONST;
import jou.cs.entity.TPlace;
import jou.cs.entity.Trend;
import jou.cs.mapper.PlaceRepository;
import jou.cs.mapper.TrendRepository;
import jou.cs.service.TrendService;
import jou.cs.utils.Recommend;
import jou.cs.utils.UserSet;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TrendsImpl implements TrendService {
    @Resource
    private TrendRepository repository;
    @Resource
    private PlaceRepository placeRepository;

    @Override
    public void record(Long uid, Long pid, String type) {

        TPlace place = placeRepository.getById(pid);

        Arrays.stream(place.getType().split(",")).forEach(p -> {
            Trend target = repository.findByUidAndTid(uid, Long.valueOf(p));

            if (target != null)
                target.setPoint(target.getPoint() + CONST.PlaceTrend.getStep(type));
            else target = Trend.builder().uid(uid).tid(Long.valueOf(p))
                    .point((long) CONST.PlaceTrend.getStep(type)).build();

            repository.save(target);
        });


    }

    @Override
    public List<UserSet.Set> getTrend(String userId) {
        // 查询所有用户id 去重
        List<Long> collect = repository.findAll().stream().map(Trend::getUid).distinct().collect(Collectors.toList());

        UserSet userSet = new UserSet();
        collect.forEach(user -> {
            List<Trend> allByUid = repository.findAllByUid(user);

            userSet.put(user.toString())
                    .set(allByUid.stream().collect(ArrayList::new, (list, trend) -> {
                        list.add(new UserSet.Set(trend.getTid().toString(), trend.getPoint()));
                    }, ArrayList::addAll))
                    .create();
        });

        Recommend recommend = new Recommend();
        List<UserSet.Set> recommendations = recommend.recommend(userId, userSet);
        System.out.println("-----------------------");
        for (UserSet.Set set : recommendations) {
            System.out.println(set.username+" "+set.score);
        }
        return recommendations;
    }
}
